import send_msg from '@feidao-factory/send-msg';
import config from '@feidao-factory/send-msg/nodejs/config';
import { v4 as uuid } from 'uuid';
import check from './_check_undefined';

interface ITableRow {
	[field: string]: number | string | boolean | null | undefined;
}

enum OpFlag {
	Delete = 2,
	Insert = 4,
	Update = 8
}

interface IArgJson {
	opflag: OpFlag;
	tname: string;
	criteria?: object;
	rowdata?: ITableRow;
}

const spaceid = config.spaceid;

/**
 * 数据保存服务
 * @param action_id 系统参数action_id
 * @param session_id 系统参数sessionid
 * @param systemid 项目的systemid
 */
export default function op(action_id: string, session_id: string, systemid: string) {
	let argjson = [] as IArgJson[];

	/**
	 * 插入数据
	 * @param tname 表名
	 * @param row 要插入的表数据，如果不包含_id字段，将自动生成_id
	 */
	function insert(tname: string, row: ITableRow) {
		if (!row._id) {
			row._id = uuid();
		}
		argjson.push({
			opflag: OpFlag.Insert,
			rowdata: row,
			tname
		});
		return row._id as string;
	}

	/**
	 * 更新数据
	 * @param tname 表名
	 * @param filter 要更新的数据条件
	 * @param row 要更新的数据
	 */
	function update(tname: string, filter: ITableRow, row: ITableRow) {
		check(filter);
		argjson.push({
			criteria: filter,
			opflag: OpFlag.Update,
			rowdata: row,
			tname
		});
	}

	/**
	 * 删除表数据
	 * @param tname 表名
	 * @param filter 要删除的数据
	 */
	function del(tname: string, filter: ITableRow) {
		check(filter);
		argjson.push({
			criteria: filter,
			opflag: OpFlag.Delete,
			tname
		});
	}

	async function exec() {
		const msg = {
			argjson,
			spaceid,
			systemid
		};
		const ret = await send_msg(action_id, session_id, 'dbacc.save.intranet', msg) as {
			code: 0 | 1;
			result: string;
		};
		argjson = [];
		return ret;
	}

	return {
		del,
		exec,
		insert,
		update
	};
}
